#include "comm/my_defs.h"
#include "comm/my_log.h"

void test_bool()
{
    my_bool_t b = MY_TRUE;
    if (!b) {
        MY_LOG_FATAL("except true, but got false");
    }

    b = MY_FALSE;
    if (b) {
        MY_LOG_FATAL("except false, but got true");
    }

    my_result_t r = MY_SUCCESS;
    if (!r) {
        MY_LOG_FATAL("except true, but got false");
    }

    r = MY_FAILED;
    if (r) {
        MY_LOG_FATAL("except false, but got true");
    }
}

void test_abs_and_swap()
{
    if (MY_ABS(100) != 100 || MY_ABS(-100) != 100) {
        MY_LOG_FATAL("except 100, but got other");
    }

    int a = 10;
    int b = 20;
    int tmp;
    MY_SWAP(a, b, tmp);
    if (a != 20 || b != 10) {
        MY_LOG_FATAL("except a = 20 && b = 10, but got other");
    }
}

void test_max_and_min()
{
    if (MY_MAX(1, 10) != 10) {
        MY_LOG_FATAL("except 10, but got other");
    }

    if (MY_MIN(1, 100) != 1) {
        MY_LOG_FATAL("except 1, but got other");
    }
}

void test_align()
{
    static int64_t size_4k = 4 * 1024;

    if (MY_ALIGN(0, size_4k) != 0 ||
        MY_ALIGN(1, size_4k) != 4096 ||
        MY_ALIGN(4095, size_4k) != 4096 ||
        MY_ALIGN(4096, size_4k) != 4096 ||
        MY_ALIGN(4097, size_4k) != 8192) {

        MY_LOG_FATAL("unexcept result");
    }

    if (MY_ALIGN_PTR(0, size_4k) != (u_char *)0 ||
        MY_ALIGN_PTR(1, size_4k) != (u_char *)4096 ||
        MY_ALIGN_PTR(4095, size_4k) != (u_char *)4096 ||
        MY_ALIGN_PTR(4097, size_4k) != (u_char *)8192) {

        MY_LOG_FATAL("unexcept result");
    }
}

typedef struct {
    uint64_t        a:38;
} my_test_type_t;

void test_castbit()
{
    uint64_t a;

    a = 123456789;  // < 2^38 - 1
    my_test_type_t t = {
        .a = MY_CASTBIT(a, 38)
    };

    if (t.a != a) {
        MY_LOG_FATAL("except %d, but got %d", a, t.a);
    }

    a = 111111111111; // < 2^38 - 1
    t.a = MY_CASTBIT(a, 38);
    if (t.a != a) {
        MY_LOG_FATAL("except %d, but got %d", a, t.a);
    }

    a = 222222222222; // < 2^38 - 1
    t.a = MY_CASTBIT(a, 38);
    if (t.a != a) {
        MY_LOG_FATAL("except %d, but got %d", a, t.a);
    }
}


int main()
{
    test_bool();
    test_abs_and_swap();
    test_max_and_min();
    test_align();
    test_castbit();

    MY_LOG_DEBUG("test pass");
    return 0;
}